<template>
    <div class="InboundList-box">
       <!-- 德育评价 -->
        <h3 class="mb16">德育评价</h3>
        <!-- 搜索栏 -->
        <serchForm :Form="inventoryForm" :FormLabel="inventoryFormLabel" @onSearch="onSearch" />
        <!-- 增删改查 -->
        <div class="function-box" v-if="checkPermi(['system:inventory:edit'])">
                <el-button class="addBtn2" @click="piliangPass">通过</el-button>
                <el-button class="delBtn2"  @click="piliangReject">拒绝</el-button>
        </div>
        <!-- 德育评价列表页面 -->
    <forTableCom
      :color="color"
      :idActive="idActive"
      :bg="bg"
      :total="totals"
      :page="pageNum"
      :limit="pageSize"
      @handleSelectionChange="handleSelectionChange"
      @handleChange="handleChange"
      @updatePage="updatePage"
      @updateLimit="updateLimit"
      :tableHeaderData="inventoryTableHeaderData"
      :tableData="inventoryTableData"
      :appraiseOperation='appraiseOperation'
      @appraiseRefuse="appraiseRefuse"
      @appraisePass="appraisePass"
      @appraisePingJia="appraisePingJia"
    >
    </forTableCom>

     <!-- 查看弹出框 -->
      <el-dialog class="custom-dialog" :title="title" v-model="open" width="1000px" append-to-body>
         <el-form :model="form" :rules="rules" label-position="top" ref="userRef" label-width="80px">
            <div class="formItembox">
              <el-form-item class="formItem" label="学号" prop="userName">
                     <el-input disabled v-model="form.userName" placeholder="" />
                  </el-form-item>
                  <el-form-item class="formItem" label="学生姓名" prop="nickName">
                     <el-input disabled v-model="form.nickName" placeholder="" />
                  </el-form-item>
                  <el-form-item class="formItem" label="所属组织" prop="deptId">
                     <el-tree-select
                     disabled
                        v-model="form.deptId"
                        :data="deptOptions"
                        :props="{ value: 'id', label: 'label', children: 'children' }"
                        node-key="id"
                        placeholder=""
                        check-strictly
                     />
                  </el-form-item>
                  <el-form-item class="formItem" label="学年" prop="schoolYear">
                     <el-input disabled v-model="form.schoolYear" placeholder="" />
                  </el-form-item>
                  <el-form-item class="formItem" label="学期" prop="termName">
                     <el-input disabled v-model="form.termName" placeholder="" />
                  </el-form-item>
                  <el-form-item class="formItem" label="获得积分" prop="creditValue">
                     <el-input disabled v-model="form.creditValue" placeholder="" />
                  </el-form-item>
                  <el-form-item class="formItem" label="个人评价">
                     <el-input disabled v-model="form.selfContent" type="textarea" placeholder=""></el-input>
                  </el-form-item>
                  <el-form-item class="formItem" label="家长评价">
                     <el-input disabled v-model="form.parentContent" type="textarea" placeholder=""></el-input>
                  </el-form-item>
                  <el-form-item class="formItem" label="教师评价">
                     <el-input v-model="form.teacherContent" type="textarea" placeholder=""></el-input>
                  </el-form-item>
                  <el-form-item class="formItem" label="企业评价/实习证明" prop="attachment">
                     <div class="file-list">
                      <div class="file-item">
                        <img class="file-img" :src="imgUrl" alt="" @click="openPhoto">
                      </div>
                     </div>
                  </el-form-item>
            </div>
         </el-form>
         <template #footer>
            <div class="dialog-footer">
               <el-button @click="cancel">取消</el-button> 
               <el-button type="primary" @click="submitForm">提交</el-button>
            </div>
         </template>
      </el-dialog>

      <!-- 通过弹出框 -->
       <el-dialog class="custom-dialog" :title="title2" v-model="open2" width="500px" append-to-body>
         <el-form :model="form2"  label-position="top" ref="userRef2" label-width="80px">
            <div>
                  <el-form-item  label="请赋分" prop="creditValue">
                     <el-input @input="changeInput"  v-model="form2.creditValue" placeholder="非必填" />
                  </el-form-item>
                  <el-form-item  label="原因">
                     <el-input  v-model="form2.content" type="textarea" placeholder="非必填"></el-input>
                  </el-form-item>
            </div>
         </el-form>
         <template #footer>
            <div class="dialog-footer">
               <el-button @click="cancel2">{{ form.userId == undefined? '重置' : '取消' }}</el-button>
               <el-button type="primary" @click="submitForm2">提交</el-button>
            </div>
         </template>
      </el-dialog>

      <!-- 拒绝弹出框 -->
       <el-dialog class="custom-dialog" :title="title3" v-model="open3" width="500px" append-to-body>
         <el-form :model="form3"  label-position="top" ref="userRef2" label-width="80px">
            <div>
                  <el-form-item  label="原因">
                     <el-input  v-model="form3.content" type="textarea" placeholder="非必填"></el-input>
                  </el-form-item>
            </div>
         </el-form>
         <template #footer>
            <div class="dialog-footer">
               <el-button @click="cancel3">{{ form.userId == undefined? '重置' : '取消' }}</el-button>
               <el-button type="primary" @click="submitForm3">提交</el-button>
            </div>
         </template>
      </el-dialog>
      <!-- 图片线上地址预览 -->
    <div v-if="showPreview" class="preview-modal" @click.self="closePreview">
      <div class="preview-content">
        <img :src="currentImage" class="preview-image" />
        <button class="close-button" @click="closePreview">
          <svg viewBox="0 0 24 24" width="24" height="24">
            <path fill="currentColor" d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/>
          </svg>
        </button>
      </div>
    </div>
    </div>
</template>

<script setup>
import { ref, reactive, toRefs,onMounted,computed } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import serchForm from '@/components/inventory/serchForm.vue'
import { checkPermi } from '@/utils/permission.js'
import forTableCom from '@/components/forTableCom/index.vue'
import { ElMessage,ElMessageBox } from 'element-plus'
import { deptTreeSelect } from "@/api/system/teacher";
import {listUser} from '@/api/semester/semesterSet.js'
import {evaluationsApi,evaluationsDetailApi,evaluationsPass,evaluationsView} from '@/api/system/appraise'

const router = useRouter();
const route = useRoute();
const data = reactive({});
const { proxy } = getCurrentInstance();

// 表单
let inventoryForm = ref({
  nickName:'',//学生姓名
  username: '', // 学号
  deptId: '', // 所属组织
  schoolYear:"",    //学年
  termIds:"",      //学期
})
// 表单数据标题
let inventoryFormLabel = ref([
  {
    name: 'nickName',
    label: '学生姓名',
  },
  {
    name: 'userName',
    label: '学号',
  },
  {
    name: 'deptId',
    label: '组织',
    type:'weixiao'
  },
  {
    name: 'schoolYear',
    label: '学年',
    type:'select',
    client: [],
  },
  {
    name: 'termName',
    label: '学期',
    type:'select',
    client: [
      {
        label:'上学期',
        value:'上学期'
      },
      {
        label:'下学期',
        value:'下学期'
      },
    ],
  },
])
// 查找
const onSearch = (v) => {
  console.log(v,'查看入库页面时间参数')
  // 每次查询后回到页1
  pageNum.value = 1
  evaluationsApiFn(v)
}

const open = ref(false);
// 显示操作栏
const appraiseOperation = ref(true)
let idActive = 'id'
// 表格
let color = ref('#333')
let bg = ref('#d9d9d93b')
// 总条目数   pageSize 加 1
let totals = ref(0)
// 当前页数
let pageNum = ref(1)
// 条数
let pageSize = ref(50)
// 存储勾选框的对象
let multipleSelection = ref([])
// 选中的列
let idList = []
const handleSelectionChange = (v) => {
  multipleSelection.value = v.map(item => item.id);
  idList = Array.from(multipleSelection.value)
}
// 分页器大小  当前分页器
const handleChange = (v) => {
  let { page, limit } = v.page
  pageNum.value = page
  pageSize.value = limit
  let params = inventoryForm.value
  evaluationsApiFn(params)
}
// 当前页面位置发生变化
const updatePage = (v) => {
  console.log(v)
}
// 条目个数发生变化
const updateLimit = (v) => {
  console.log(v)
}
// 表格表头数据
let inventoryTableHeaderData = ref([
  {
    prop: 'nickName',
    label: '学生姓名',
    minwidth: 120,
  },
  {
    prop: 'userName',
    label: '学号',
  },
  {
    prop: 'deptNameList',
    label: '组织',
    minwidth: 240,
    enterpriseDeptShow:true
  },
  {
    prop: 'schoolYear',
    label: '学年',
    minwidth: 120,
  },
  {
    prop: 'termName',
    label: '学期',
    minwidth: 120,
  },
  {
    prop: 'teacherContent',
    label: '教师评价',
    minwidth: 120,
  },
  {
    prop: 'parentContent',
    label: '家长评价',
    minwidth: 120,
  },
  {
    prop: 'companyContent',
    label: '企业评价',
    minwidth: 120,
  },
  {
    prop: 'selfContent',
    label: '个人评价',
    minwidth: 120,
  },
  {
    prop: 'creditValue',
    label: '获得积分',
    minwidth: 120,
  },
  {
    prop: 'status',
    label: '状态',
    minwidth: 120,
    pageType:'qiyeStatus'
  },
  {
    prop: 'rejectReason',
    label: '原因',
    minwidth: 180,
  },
])
// 表格数据内容
let inventoryTableData = ref([])
const appraiseRefuse = (val)=>{  //拒绝
      let {i , v} = val
      passId.value = v.id
      open3.value = true
}

const open2 = ref(false);
const open3 = ref(false);
const form2 = ref({
     creditValue:'',      //赋分
     content:'',        //备注原因内容
  })
const form3 = ref({
     content:'',        //备注原因内容
  })
const title = ref('查看评价')
const title2 = ref('通过')
const title3 = ref('拒绝')
const passId = ref('')
const appraisePass = (val)=>{ //打开通过弹出框
    let {i , v} = val
    passId.value = v.id
    open2.value = true
}
const changeInput = (value)=>{
    // 正则表达式：允许数字 + 可选的一位小数
  const reg = /^(\d+\.?\d{0,1}|\d*)$/;
  
  // 如果输入不符合规则，则还原为上一次的合法值
  if (!reg.test(value)) {
    // 这里可以阻止非法输入（如直接过滤掉非法字符）
    form.value.creditValue = form.value.creditValue.replace(/[^\d.]/g, ''); // 移除非数字和小数点
    form.value.creditValue = form.value.creditValue.replace(/(\.\d*)\./g, '$1'); // 防止多个小数点
    form.value.creditValue = form.value.creditValue.replace(/(\.\d{1})\d+/g, '$1'); // 只保留一位小数
  }
}
const submitForm2 = ()=>{  //通过按钮
    let obj = {
       id:passId.value,
       status:1,
       creditValue:form2.value.creditValue,
       content:form2.value.content,
       ids:  idList.length > 0 ? idList : [passId.value] 
    }
      evaluationsPass(obj).then(res => {
      console.log(res,'打印通过接口');
       if(res.code===200){
           ElMessage({
                 message: '已通过',
                 type: 'success',
               })
               open2.value = false
               evaluationsApiFn()
       }
    });
}
const submitForm3 = ()=>{  //拒绝按钮
    let obj = {
       id:passId.value,
       status:2,
       content:form3.value.content,
       ids:  idList.length > 0 ? idList : [passId.value] 
    }
      evaluationsPass(obj).then(res => {
      console.log(res,'打印拒绝接口');
       if(res.code===200){
           ElMessage({
                 message: '已拒绝',
                 type: 'success',
               })
               open3.value = false
               evaluationsApiFn()
       }
    });
}

let imgUrl = ref('')
const appraisePingJia = async(val)=>{ //查看按钮
    let {i , v} = val
    passId.value = v.id
    open.value = true
  let { code, data } = await evaluationsDetailApi(v.id)
     if(code===200){
         form.value.userName = data.userName
         form.value.nickName = data.nickName
         form.value.deptId = data.deptId
         if(data.attachment){
             imgUrl.value = data.attachment
         }
          form.value.termName = data.termName
          form.value.creditValue = data.creditValue
          form.value.schoolYear = data.schoolYear
          form.value.selfContent = data.selfContent
          form.value.parentContent = data.parentContent
          form.value.teacherContent = data.teacherContent
         console.log(data,'打印详情数据');
         
     }
}
const submitForm = ()=>{ //查看提交
          let obj = {
        id:passId.value,
        teacherContent:form.value.teacherContent,
    }
          evaluationsView(obj).then(res=>{
         if(res.code===200){
             ElMessage({
                 message: '修改成功',
                 type: 'success',
               })
               open.value = false
               evaluationsApiFn()
         }
    })
}
const piliangPass = ()=>{ //批量通过
  if(multipleSelection.value.length===0){
       ElMessage({
                 message: '请先选择要通过的数据',
                 type: 'error',
               })
      return false
  }
  form2.value.creditValue = ''
  form2.value.content = ''
  open2.value = true
}
const piliangReject = ()=>{  //批量拒绝
  if(multipleSelection.value.length===0){
       ElMessage({
                 message: '请先选择要拒绝的数据',
                 type: 'error',
               })
      return false
  }
  form3.value.content = ''
  open3.value = true
}
const cancel = ()=>{ 
   open.value = false
}
const cancel2 = ()=>{ 
   open2.value = false
}
const cancel3 = ()=>{ 
   open3.value = false
}

//图片预览
const showPreview = ref(false);
const currentImage = ref('');
//打开预览
const openPhoto = ()=>{
         currentImage.value = imgUrl.value;
         showPreview.value = true;
         document.body.style.overflow = 'hidden'; // 防止背景滚动
}
// 关闭预览
const closePreview = () => {
  showPreview.value = false;
  document.body.style.overflow = '';
};
// 点击ESC键关闭预览
const handleKeyDown = (e) => {
  if (e.key === 'Escape' && showPreview.value) {
    closePreview();
  }
};
// 添加键盘事件监听
window.addEventListener('keydown', handleKeyDown);
onMounted(()=>{
    
})

const form = ref({
     nickName:'',      //学生姓名
     deptId:'',        //所属组织
     userName:'',   //学号
     attachment:'', //企业文件
     userId:'',
     termName:'',    //学期
     creditValue:'',  //获得积分
     schoolYear:'',   //学年
     selfContent:'',   //个人评价
     parentContent:'',  //家长评价
     teacherContent:'',  //教师评价
  })

// const rules = ref({
//     userName: [{ required: true, message: "请输入正确的工号", trigger: "blur" }],
//     nickName: [{ required: true, message: "用户昵称不能为空", trigger: "blur" }],
//     password: [{ required: true, message: "用户密码不能为空", trigger: "blur" }, { min: 5, max: 20, message: "用户密码长度必须介于 5 和 20 之间", trigger: "blur" }],
//     roleIds: [{ required: true, message: "请选择角色", trigger: "change"}],
//     deptId: [{ required: true, message: "请选择所属组织", trigger: "change"}],
//   })
const deptOptions = ref(undefined);
/** 查询组织下拉树结构 */
function getDeptTree() {
  deptTreeSelect().then(response => {
    deptOptions.value = response.data;
  });
};
// 获取学期下拉信息
const listUserFn = async () => {
  let page = {
    pageNum: 1,
    pageSize: -1,
  }
  let {code, rows} = await listUser(page)
  if (code === 200) {
  rows.forEach((v) => {
    inventoryFormLabel.value[3].client.push({
      value: v.schoolYear,
      label: v.schoolYear,
    })
  })
  }
}
// 查询评价列表数据
const evaluationsApiFn = async (data = '') => {
  let page = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    // evaluatorType:3
  }
  let params = Object.assign(data, page)
  let res = await evaluationsApi(params)
  let { code, rows } = res
  if (code == 200) {
    console.log(rows,'打印评价列表数据');
    totals.value = res.total
    inventoryTableData.value = rows
  }
}
onMounted(()=>{
  Promise.all([getDeptTree(),evaluationsApiFn(),listUserFn()])
})
</script>

<style lang='scss' scoped>
.InboundList-box {
    padding: 16px;
    .function-box {
    display: flex;
    align-items: center;
  }
}
.formItembox {
      display: flex;
      flex-wrap: wrap;
      box-sizing: border-box;

      .formItem {
        width: 28%;
        // display: flex;
        margin-right: 76px;
      }
      .formItem:last-child {
        width: 100%;
        margin-right:0;
      }
      .formItem:nth-child(3) {
        margin-right:0;
      }
      .formItem:nth-child(6) {
        margin-right:0;
      }
      .formItem:nth-child(7) {
        width: 100%;
        margin-right:0;
      }
      .formItem:nth-child(8) {
        width: 100%;
        margin-right:0;
      }
      .formItem:nth-child(9) {
        width: 100%;
        margin-right:0;
      }
      .formItem:nth-child(10) {
        width: 100%;
        margin-right:0;
        .file-list{
           width: 100%;
           border: 1px solid #ccc;
           display: flex;
           justify-content: center;
           padding: 10px 0;
           .file-item{
            width: 200px;
            height: 200px;
              .file-img{
                 width: 100%;
                 height: 100%;
              }
           }
        }
      }
    }
:deep(.el-select .el-input__wrapper) {
  width: 269px;
}
.dialog-footer {
  display: flex;
  justify-content: center; /* 水平居中 */
  margin-top: -25px;
}
:deep(.el-textarea__inner){
    height: 80px;
}

/* 图片预览样式 */
.preview-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.preview-content {
  position: relative;
  max-width: 90%;
  max-height: 90%;
}

.preview-image {
  max-width: 100%;
  max-height: 90vh;
  object-fit: contain;
  border-radius: 4px;
}

.close-button {
  position: absolute;
  top: -40px;
  right: -40px;
  background: none;
  border: none;
  color: white;
  cursor: pointer;
  font-size: 24px;
  padding: 10px;
  transition: transform 0.2s;
}

.close-button:hover {
  transform: scale(1.2);
}

@media (max-width: 768px) {
  .close-button {
    top: -50px;
    right: 10px;
  }
}

</style>

